/**
 * 文件操作模块使用演示
 * 展示如何使用FileOperations接口进行各种文件操作
 */

import { fileOperations } from '../file-operations'
import type { CopyOperation } from '../../types'

/**
 * 演示基础文件操作
 */
async function demonstrateBasicOperations() {
  console.log('=== 基础文件操作演示 ===')
  
  try {
    // 1. 写入文件
    console.log('1. 写入文件...')
    const testContent = `
# 测试文件
这是一个测试文件，创建时间：${new Date().toISOString()}

## 内容
- 项目：文件历史版本管理工具
- 模块：文件操作演示
- 功能：展示基础文件操作
    `
    
    await fileOperations.writeFile('demo-output/test.md', testContent)
    console.log('✓ 文件写入成功')

    // 2. 检查文件是否存在
    console.log('2. 检查文件存在性...')
    const exists = await fileOperations.fileExists('demo-output/test.md')
    console.log(`✓ 文件存在: ${exists}`)

    // 3. 读取文件内容
    console.log('3. 读取文件内容...')
    const readContent = await fileOperations.readFile('demo-output/test.md')
    console.log(`✓ 读取成功，内容长度: ${readContent.length} 字符`)

    // 4. 获取文件统计信息
    console.log('4. 获取文件统计信息...')
    const stats = await fileOperations.getFileStats('demo-output/test.md')
    console.log(`✓ 文件大小: ${stats.size} 字节`)
    console.log(`✓ 修改时间: ${stats.modifiedTime.toISOString()}`)
    console.log(`✓ 是否为目录: ${stats.isDirectory}`)

    // 5. 复制文件
    console.log('5. 复制文件...')
    await fileOperations.copyFile('demo-output/test.md', 'demo-output/backup/test-copy.md')
    console.log('✓ 文件复制成功')

  } catch (error) {
    console.error('❌ 基础操作失败:', error)
  }
}

/**
 * 演示批量文件操作
 */
async function demonstrateBatchOperations() {
  console.log('\n=== 批量文件操作演示 ===')
  
  try {
    // 1. 创建多个测试文件
    console.log('1. 创建测试文件...')
    const testFiles = [
      { name: 'document1.txt', content: '这是第一个文档' },
      { name: 'document2.txt', content: '这是第二个文档' },
      { name: 'document3.txt', content: '这是第三个文档' },
      { name: 'config.json', content: '{"version": "1.0.0", "name": "demo"}' },
      { name: 'readme.md', content: '# 演示项目\n\n这是一个演示项目。' }
    ]

    for (const file of testFiles) {
      await fileOperations.writeFile(`demo-output/source/${file.name}`, file.content)
    }
    console.log(`✓ 创建了 ${testFiles.length} 个测试文件`)

    // 2. 准备批量复制操作
    console.log('2. 准备批量复制操作...')
    const copyOperations: CopyOperation[] = testFiles.map(file => ({
      sourcePath: `demo-output/source/${file.name}`,
      targetPath: `demo-output/batch-target/${file.name}`,
      overwrite: true
    }))

    // 3. 执行批量复制
    console.log('3. 执行批量复制...')
    const startTime = Date.now()
    const result = await fileOperations.batchCopyFiles(copyOperations)
    const endTime = Date.now()

    console.log(`✓ 批量操作完成，耗时: ${endTime - startTime}ms`)
    console.log(`✓ 成功: ${result.successful.length} 个文件`)
    console.log(`✓ 失败: ${result.failed.length} 个文件`)
    console.log(`✓ 总计: ${result.totalCount} 个文件`)

    // 4. 显示失败的操作（如果有）
    if (result.failed.length > 0) {
      console.log('失败的操作:')
      result.failed.forEach(failed => {
        console.log(`  - ${failed.sourcePath} -> ${failed.targetPath}: ${failed.error}`)
      })
    }

  } catch (error) {
    console.error('❌ 批量操作失败:', error)
  }
}

/**
 * 演示错误处理
 */
async function demonstrateErrorHandling() {
  console.log('\n=== 错误处理演示 ===')
  
  // 1. 读取不存在的文件
  console.log('1. 尝试读取不存在的文件...')
  try {
    await fileOperations.readFile('nonexistent-file.txt')
  } catch (error: any) {
    console.log(`✓ 捕获到预期错误: ${error.type} - ${error.message}`)
  }

  // 2. 复制不存在的源文件
  console.log('2. 尝试复制不存在的源文件...')
  try {
    await fileOperations.copyFile('nonexistent-source.txt', 'demo-output/target.txt')
  } catch (error: any) {
    console.log(`✓ 捕获到预期错误: ${error.type} - ${error.message}`)
  }

  // 3. 批量操作中的部分失败
  console.log('3. 演示批量操作中的部分失败...')
  try {
    // 创建一个存在的文件和一个不存在的文件的复制操作
    await fileOperations.writeFile('demo-output/existing.txt', '存在的文件')
    
    const mixedOperations: CopyOperation[] = [
      {
        sourcePath: 'demo-output/existing.txt',
        targetPath: 'demo-output/copy-existing.txt',
        overwrite: true
      },
      {
        sourcePath: 'demo-output/nonexistent.txt', // 不存在的文件
        targetPath: 'demo-output/copy-nonexistent.txt',
        overwrite: true
      }
    ]

    const result = await fileOperations.batchCopyFiles(mixedOperations)
    console.log(`✓ 部分成功演示: 成功 ${result.successful.length}, 失败 ${result.failed.length}`)
    
    if (result.failed.length > 0) {
      console.log('失败详情:')
      result.failed.forEach(failed => {
        console.log(`  - ${failed.error}`)
      })
    }

  } catch (error) {
    console.error('❌ 错误处理演示失败:', error)
  }
}

/**
 * 演示目录操作
 */
async function demonstrateDirectoryOperations() {
  console.log('\n=== 目录操作演示 ===')
  
  try {
    // 1. 创建嵌套目录
    console.log('1. 创建嵌套目录结构...')
    const directories = [
      'demo-output/nested/level1/level2',
      'demo-output/project/src/components',
      'demo-output/project/src/services',
      'demo-output/project/tests/unit',
      'demo-output/project/tests/integration'
    ]

    for (const dir of directories) {
      await fileOperations.ensureDirectory(dir)
    }
    console.log(`✓ 创建了 ${directories.length} 个目录结构`)

    // 2. 在目录中创建文件
    console.log('2. 在目录中创建文件...')
    const projectFiles = [
      { path: 'demo-output/project/src/components/Header.vue', content: '<template><header>Header</header></template>' },
      { path: 'demo-output/project/src/services/api.ts', content: 'export const api = {}' },
      { path: 'demo-output/project/tests/unit/header.test.ts', content: 'describe("Header", () => {})' },
      { path: 'demo-output/project/package.json', content: '{"name": "demo-project", "version": "1.0.0"}' }
    ]

    for (const file of projectFiles) {
      await fileOperations.writeFile(file.path, file.content)
    }
    console.log(`✓ 在目录结构中创建了 ${projectFiles.length} 个文件`)

    // 3. 检查目录统计信息
    console.log('3. 检查目录统计信息...')
    const dirStats = await fileOperations.getFileStats('demo-output/project')
    console.log(`✓ 目录统计: 大小 ${dirStats.size} 字节, 是目录: ${dirStats.isDirectory}`)

  } catch (error) {
    console.error('❌ 目录操作失败:', error)
  }
}

/**
 * 演示性能测试
 */
async function demonstratePerformance() {
  console.log('\n=== 性能测试演示 ===')
  
  try {
    // 1. 大文件操作性能
    console.log('1. 大文件操作性能测试...')
    const largeContent = 'A'.repeat(1024 * 100) // 100KB
    
    const startWrite = Date.now()
    await fileOperations.writeFile('demo-output/large-file.txt', largeContent)
    const writeTime = Date.now() - startWrite
    
    const startRead = Date.now()
    const readContent = await fileOperations.readFile('demo-output/large-file.txt')
    const readTime = Date.now() - startRead
    
    console.log(`✓ 大文件写入耗时: ${writeTime}ms`)
    console.log(`✓ 大文件读取耗时: ${readTime}ms`)
    console.log(`✓ 内容验证: ${readContent.length === largeContent.length ? '通过' : '失败'}`)

    // 2. 批量小文件操作性能
    console.log('2. 批量小文件操作性能测试...')
    const fileCount = 20
    const operations: CopyOperation[] = []
    
    // 创建源文件
    for (let i = 0; i < fileCount; i++) {
      const sourcePath = `demo-output/perf-source/file${i}.txt`
      await fileOperations.writeFile(sourcePath, `Content for file ${i}`)
      
      operations.push({
        sourcePath,
        targetPath: `demo-output/perf-target/file${i}.txt`,
        overwrite: true
      })
    }
    
    const startBatch = Date.now()
    const batchResult = await fileOperations.batchCopyFiles(operations)
    const batchTime = Date.now() - startBatch
    
    console.log(`✓ 批量复制 ${fileCount} 个文件耗时: ${batchTime}ms`)
    console.log(`✓ 平均每文件: ${(batchTime / fileCount).toFixed(2)}ms`)
    console.log(`✓ 成功率: ${(batchResult.successful.length / batchResult.totalCount * 100).toFixed(1)}%`)

  } catch (error) {
    console.error('❌ 性能测试失败:', error)
  }
}

/**
 * 主演示函数
 */
async function runDemo() {
  console.log('🚀 文件操作模块演示开始\n')
  
  try {
    await demonstrateBasicOperations()
    await demonstrateBatchOperations()
    await demonstrateErrorHandling()
    await demonstrateDirectoryOperations()
    await demonstratePerformance()
    
    console.log('\n✅ 所有演示完成！')
    console.log('\n📁 演示文件已创建在 demo-output/ 目录中')
    console.log('你可以查看这些文件来验证操作结果。')
    
  } catch (error) {
    console.error('\n❌ 演示过程中发生错误:', error)
  }
}

// 如果直接运行此文件，则执行演示
if (import.meta.url === `file://${process.argv[1]}`) {
  runDemo().catch(console.error)
}

export { runDemo }